/*
 * @Descripttion: 核酸宝项目前端
 * @version: 
 * @Author: 杜宇轩
 * @Date: 2022-05-22 05:23:33
 * @LastEditors: 杜宇轩
 * @LastEditTime: 2022-05-22 06:17:05
 */
import commonUser from "@/store/modules/commonUser";
import volunteer from "@/store/modules/volunteer";
import approver from "@/store/modules/approver";
import admin from "@/store/modules/admin";
import userInfo from "@/store/modules/userInfo";

const plugin = (store) => { // 配置哪个模块需要持久化存储
  subscribe('commonUser', store, commonUser);
  subscribe('volunteer', store, volunteer);
  subscribe('approver', store, approver);
  subscribe('admin', store, admin);
  subscribe('userInfo', store, userInfo);
}

// 数据持久化存入localStorage中
const subscribe = (type, store, module) => {
  if (initState(type, store)) {
    console.log('[SyncStorage.subscribe] init ' + type + ' success');
  } else {
    console.error('[SyncStorage.subscribe] No ' + type + ' state in localStorage');
  }

  store.subscribe((mutation, state) => {
    if (mutation.type.indexOf(type) > -1) {
      const name = mutation.type.replace(type + '/', '');
      const typeMutations = getModuleOptions(module, 'mutations');
      if (typeMutations.includes(name)) {
        localStorage.setItem('NATMS_' + type, JSON.stringify(state[type]));
      }
    }
  });
}

// 从localStorage获取数据
const initState = (type, store) => {
  const state = localStorage.getItem('NATMS_' + type);
  if (state) {
    const data = JSON.parse(state);
    store.commit(type + '/SET_DATA', data);
    return true;
  }
  return false;
}

// 检查module的mutations中是否含有该函数
const getModuleOptions = (module, key) => {
  if (!module || !module[key]) return [];
  return Object.keys(module[key]);
};

export default plugin;
